/**
 * Copyright @ 2023 iAuto (Shanghai) Co., Ltd.
 * All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are NOT permitted except as agreed by
 * iAuto (Shanghai) Co., Ltd.
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 */

import React, { useCallback, useState } from 'react';
import classNames from 'classnames';
import { Row, Col, Modal, message } from 'antd';
import { connect } from 'dva';
import { useLocation } from 'react-router-dom';
import { ToolboxWidth } from '@/lib/blocks-vm';
import styles from './index.less';
import log from '@/lib/log';
import { router } from 'umi';
import {
  checkCompetingRelationship,
  checkProjectJson,
  filterProjectJson,
  replaceUrlParams,
} from '@/utils';
import IdeButton from '../IdeButton';
import { sceneUpload } from '@/services/httpService';
import { useMount } from 'ahooks';
import { checkPlaceholdersAndParams, replaceBackward, replaceDateCustomData } from '@/utils/block';
import { findOpcodeKey, separateAndGroupBlocks, separateBlocksByKey } from '@/utils/blocks';

interface ITitle {
  blockSize:
    | {
        height: number;
        width: number;
      }
    | undefined;
  title?: string;
  projectChanged?: boolean;
  vm?: any;
  id?: any;
  clear?: () => void;
  save?: () => void;
  setId?: (id: any) => void;
  userId: string;
  name: string;
  dispatch: any;
  history: any;
  editGlobal: any;
}

const mapStateToProps = (state: any) => ({
  editGlobal: state.editGlobal,
});

const Title: React.FC<ITitle> = ({ dispatch, ...props }) => {
  const { blockSize, clear, vm, id, name, setId, editGlobal } = props;
  const location = useLocation();
  const query = location.query;

  const [brandInfo, setBrandInfo] = useState({
    brandName: '',
    brandCode: '',
  });

  const { sceneJson, skillJson, fileMap, markBlocksMap } = editGlobal;

  useMount(() => {
    // dispatch({
    //   type: 'editGlobal/setLoading',
    //   payload: {
    //     apiName: '/common/vehicle/getcurrentbrand',
    //     loading: true,
    //   },
    // });
    dispatch({
      type: 'vehicleInfoQuery/getData',
      payload: {
        url: '/common/vehicle/getcurrentbrand',
      },
      callback: (e: any) => {
        setBrandInfo({
          brandName: e?.data?.[0]?.brandName,
          brandCode: e?.data?.[0]?.brandCode,
        });
        // dispatch({
        //   type: 'editGlobal/setLoading',
        //   payload: {
        //     apiName: '/common/vehicle/getcurrentbrand',
        //     loading: false,
        //   },
        // });
      },
    });
  });

  const getTitleWidth = useCallback(() => {
    if (blockSize) {
      return blockSize.width - ToolboxWidth;
    }
    return 0;
  }, [blockSize]);

  // 读取原始数据
  const readProjectJson = useCallback(() => {
    const json = JSON.parse(vm.toJSON());
    const { length } = json.targets;
    if (length) {
      return json.targets[length - 1].blocks;
    } else {
      log.warn('获取json targets异常');
      return {};
    }
  }, [vm]);

  const save = useCallback(
    async (blockJson: any) => {
      let newBlockJson = blockJson;
      console.log('🚀 ~ file: index.tsx ~ line 124 ~ newBlockJson', newBlockJson);
      const markIds = (markBlocksMap as Map<string, any>).get('markIds') || [];
      const dateCustomList = (markBlocksMap as Map<string, any>).get('date_custom') || [];

      // 判断有没有 占位符不匹配的场景数据
      if (checkPlaceholdersAndParams(newBlockJson, markIds)) {
        // 处理数据 传入json 传入
        // log.warn('存在占位符不匹配的场景数据');
        // 补充默认值
        // 读取文件id
        newBlockJson = replaceBackward(newBlockJson, skillJson, markIds, fileMap);
      }

      // 判断存不存在 date_custom 场景数据
      if (checkPlaceholdersAndParams(newBlockJson, dateCustomList)) {
        // 处理数据 传入json 传入
        // log.warn('存在date_custom的场景数据');
        newBlockJson = replaceDateCustomData(newBlockJson, skillJson, dateCustomList);
      }

      dispatch({
        type: 'editGlobal/setLoading',
        payload: {
          apiName: 'sceneUpload',
          loading: true,
        },
      });

      const { statusCode, data } = await sceneUpload({
        sceneUuid: id || '',
        modelCode: query.modelCode || '',
        seriesCode: query.seriesCode || '',
        brandCode: brandInfo.brandCode || localStorage.getItem('x-brand-code') || 'Warrior',
        brandName: brandInfo.brandName || localStorage.getItem('x-brand-code') || 'Warrior',
        blocks: JSON.stringify(newBlockJson),
        name: sceneJson.name || name,
        description: sceneJson.description || '',
        version: sceneJson.version || '',
        // socVersion: 'default',
        iconUrl: sceneJson.iconUrl || '',
        backgroundUrl: sceneJson.backgroundUrl || '',
      });

      dispatch({
        type: 'editGlobal/setGlobalState',
        payload: {
          projectChanged: false,
        },
      });

      if (statusCode === '0') {
        // 不存在id
        if (!id) {
          // 设置id
          setId?.(data);
          // 替换浏览器参数
          replaceUrlParams({ sceneUuid: data, name: name });

          // setTimeout(() => {
          //   // 获取 场景详情
          //   dispatch({
          //     type: 'editGlobal/getSceneJson',
          //     payload: {
          //       sceneUuid: data,
          //       modelCode: query.modelCode,
          //       seriesCode: query.seriesCode
          //     }
          //   });
          // }, 200);
        }

        // 提示
        message.success('保存成功');
        await dispatch({
          type: 'editGlobal/setLoading',
          payload: {
            apiName: 'sceneUpload',
            loading: false,
          },
        });

        setTimeout(() => {
          // 跳转场景详情
          router.push('/soaManage/scene/official/edit?sceneUuid=' + (id || data));
        }, 200);
      }
    },
    [dispatch, setId, sceneJson, query, name, id, brandInfo, skillJson, fileMap, markBlocksMap],
  );

  const showModal = async (newBlockJson: any, warningList: string[] = []) => {
    if (warningList.length) {
      Modal.confirm({
        title: '竞合关系冲突',
        width: 600,
        content: (
          <div
            style={{
              overflowY: 'auto',
              maxHeight: 300,
            }}
          >
            {warningList.map((item, index) => (
              <p key={index}>{item}</p>
            ))}
          </div>
        ),
        okText: '保存',
        cancelText: '取消',
        onOk() {
          save(newBlockJson);
        },
      });
    } else {
      save(newBlockJson);
    }
  };

  const handleSave = useCallback(async () => {
    try {
      // 读取当前场景数据
      const blockJson = readProjectJson();

      // 如果场景数据为空，提醒用户添加场景内容
      if (JSON.stringify(blockJson) === '{}') {
        const msg = '场景内容必须添加到当前，请添加当前。';
        log.log(msg);
        message.warning(msg);
        return;
      }

      // 读取分离后的场景数据 以及 对应的隔离数据
      const { groupBlocks, separateBlockList } = separateBlocksByKey(blockJson);

      // 获取当前 JSON 中所有的 action id
      const actionIds = skillJson.filter((item: any) => !item.mType).map((item: any) => item.mID);

      // 验证数据全场景状态
      const errList = checkProjectJson(groupBlocks, actionIds);

      // 如果存在错误，提醒用户并返回
      if (errList.length) {
        log.log(errList[0].msg);
        message.warning(errList[0].msg);
        return;
      }

      let allWarningList: string[] = [];

      separateBlockList.forEach(separateBlock => {
        const { warningList } = checkCompetingRelationship(separateBlock);
        allWarningList = allWarningList.concat(warningList);
      });

      // 根据竞合关系状态调用 showModal
      showModal(groupBlocks, allWarningList);
    } catch (error) {
      // 处理异常情况，输出错误日志并设置 loading 状态
      console.error('🚀 ~ file: index.tsx ~ line 47 ~ handleSave ~ error', error);
      dispatch({
        type: 'editGlobal/setLoading',
        payload: {
          apiName: 'sceneUpload',
          loading: false,
        },
      });
    }
  }, [readProjectJson, query, id, save, skillJson]);

  return (
    <div
      className={classNames(styles.titleComponet)}
      style={{
        width: getTitleWidth(),
      }}
    >
      {getTitleWidth() && (
        <Row style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          {/* <Col className={classNames(styles.title)}>{title}</Col> */}
          <Col className={classNames(styles.tips)}>
            <h2>{name}</h2>
            注：自动吸附的拼图可合成为一个场景，无法吸附的拼图说明不会存在场景中，拖拽拼图离开主线程后该拼图会变成半透明。
          </Col>
          <Col style={{ display: 'flex' }}>
            <IdeButton
              style={{ marginRight: 16 }}
              className={classNames(styles.btn)}
              onClick={clear}
            >
              清空积木
            </IdeButton>
            <IdeButton className={classNames(styles.btn, styles.save)} onClick={() => handleSave()}>
              保存
            </IdeButton>
          </Col>
        </Row>
      )}
    </div>
  );
};

export default connect(mapStateToProps)(Title);
